package com.neusoft.springdemo.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.neusoft.springdemo.bean.Admin;

/**
 * <pre>
 *    mvc框架的常用功能：
 *      1.跳转控制（请求分发）
 *      2.数据的接收和转换
 *      3.spring 控制器接收参数的3种方法
 *      4.spring mvc控制器返回数据的4种方法
 * 
 * 
 * </pre>
 * 
 * @author chens
 *
 */
@Controller
@RequestMapping("/admin")
public class AdminController {
	private Logger logger = Logger.getLogger(AdminController.class);

	/**
	 * <pre>
	 * 1.在控制器方法中定义参数，接收参数
	 * 2.默认的方法参数名称与客户端发送的参数一致，
	 * 3.可以使用@RequestParam注解配置客户端参数的名称，默认值和是否必须参数
	 * 
	 * </pre>
	 * 
	 * @param page
	 * @param size
	 * @return 返回string类型指定的视图
	 */
	@RequestMapping("list.do")
	public String list(@RequestParam(value = "p", required = true, defaultValue = "1") Integer page,
			@RequestParam(value = "s", defaultValue = "10") Integer size, String[] c) {
		logger.info(page + "<><><><><>>><<" + size);
		if (c != null) {
			logger.info(c.length);
			logger.info(c);
		}

		return "admin_list";
	}

	/**
	 * 可以使用对象接收参数，spring mvc会完成数据的接收、转换和封装
	 * 
	 * @param admin
	 * @return
	 */
	@RequestMapping("add.do")
	public String add(Admin admin) {
		logger.info("===================================");
		logger.info(admin);

		return "admin_list";
	}

	/**
	 * 使用servlet技术接收参数
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "edit.do")
	public String edit(HttpServletRequest request, HttpServletResponse response) {
		String adminName = request.getParameter("adminName");
		String password = request.getParameter("password");

		logger.info(adminName + "<><><><><>   " + password);

		return "admin_list";
	}

	/**
	 * 返回void类型，需要使用HTTPServletResponse返回
	 * 
	 * @param admin
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value = "add3.do")
	public void add2(Admin admin, HttpServletResponse response) throws IOException {

		logger.info("<><><><><>   " + admin);

		response.setContentType("application/json;charset=UTF8");
		response.getWriter().write("{'success':true,'msg':'success'}");
		response.getWriter().flush();
	}

	@RequestMapping(value = "add2.do")
	public void add2(HttpServletRequest request, HttpServletResponse response) throws IOException {

		logger.info("<><><><><>   ");

		StringBuilder sb = new StringBuilder();
		BufferedReader reader = request.getReader();
		char[] buf = new char[1024];
		int len;
		while ((len = reader.read(buf)) != -1) {
			sb.append(buf, 0, len);
		}

		// 使用Jackson的jar包中的ObjectMapper进行java对象与jose数据的转换
		// Gson gonGson = new Gson();

		ObjectMapper om = new ObjectMapper();

		String jsonString = sb.toString();
		System.out.println(jsonString);

		// Admin admin = gonGson.fromJson(jsonString, Admin.class);
		Admin admin = om.readValue(jsonString, Admin.class);

		logger.info(admin.getAdminName() + "<><><><><>   " + admin.getPassword());

		response.setContentType("application/json;charset=UTF8");
		response.getWriter().write("{'success':true,'msg':'success'}");
		response.getWriter().flush();
	}

	/**
	 * 
	 * @param id
	 * @return 返回string并使用@ResponseBody指定返回主体
	 */
	@RequestMapping("delete.do")
	@ResponseBody
	public String delete(@RequestParam(defaultValue = "0") Integer id) {
		logger.info("======================");

		return "{'success':true,'msg':'success'}";
	}

	@RequestMapping("/list2.do")
	@ResponseBody
	public String list2() {
		logger.info("======================");

		List<Admin> list = new ArrayList<Admin>();

		list.add(new Admin(1, "root", "12345678"));
		list.add(new Admin(1, "root", "12345678"));
		list.add(new Admin(1, "root", "12345678"));
		list.add(new Admin(1, "root", "12345678"));
		list.add(new Admin(1, "root", "12345678"));
		list.add(new Admin(1, "root", "12345678"));

		String jsonString = new Gson().toJson(list);

		return jsonString;
	}

	/**
	 * 直接返回对象，需要在spring-mvc中配置json转换器
	 * 
	 * 
	 * @return
	 */
	@RequestMapping("/list3.do")
	@ResponseBody
	public List<Admin> list3() {
		logger.info("======================");

		List<Admin> list = new ArrayList<Admin>();

		list.add(new Admin(1, "root", "12345678"));
		list.add(new Admin(1, "root", "12345678"));
		list.add(new Admin(1, "root", "12345678"));
		list.add(new Admin(1, "root", "12345678"));
		list.add(new Admin(1, "root", "12345678"));
		list.add(new Admin(1, "root", "12345678"));

		return list;
	}

}
